<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-calendar"></i> 用户管理 </el-breadcrumb-item>
                <el-breadcrumb-item>用户信息</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
                <el-row>
                    <el-col :span="11">
                         <div class="form-box" >
                            <el-form ref="form" :model="form" label-width="80px" :rules="rules">

                                <el-form-item label="员工编号" >
                                    <el-input v-model="form.tid" disabled></el-input>
                                </el-form-item>

                                <el-form-item label="用户名" prop="userName">
                                    <el-input v-model="form.userName" disabled></el-input>
                                </el-form-item>
                      

                                <el-form-item label="昵称" prop="nickName">
                                    <el-input v-model="form.nickName"></el-input>
                                </el-form-item>
                
                                  <el-form-item label="创建时间">
                                    <el-date-picker
                                        v-model="user.createTime"
                                        type="datetime"
                                        :format="dateformat"
                                        placeholder="选择日期时间"
                                        disabled>
                                    </el-date-picker>
                                </el-form-item>

                                <el-form-item label="更新时间">
                                    <el-date-picker
                                        v-model="user.updateTime"
                                        type="datetime"
                                        :format="dateformat"
                                        placeholder="暂未更新"
                                        disabled>
                                    </el-date-picker>
                                </el-form-item>

                                <el-form-item label="最后登录">
                                    <el-date-picker
                                        v-model="user.lastTime"
                                        type="datetime"
                                        :format="dateformat"
                                        placeholder="无"
                                        disabled>
                                    </el-date-picker>
                                </el-form-item>

                                <el-form-item label="角色">
                                    <el-checkbox-group v-model="form.roles">
                                        <el-tag   v-for="(item, index) in roles" :key="index">{{
                                            item.name
                                        }}</el-tag>
                                    </el-checkbox-group>
                                </el-form-item>
                                <el-form-item>
                                    <el-button @click="goback" icon="el-icon-arrow-left">返回</el-button>
                                    <el-button type="primary" @click="onSubmit('form')" icon="el-icon-edit">更改用户</el-button>
                                    <el-button type="warning" @click="reset('form')" icon="el-icon-refresh-right">重置</el-button>
                                    <el-button type="danger" @click="dialogFormVisible=true" icon="el-icon-edit-outline">更改密码</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                </el-col>
                    <el-col :span="11">
                        <el-upload
                            class="avatar-uploader"
                            action="http://localhost:8090/icon"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="this.form.iconUrl" :src="this.form.iconUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-col>
                </el-row>

                <el-dialog title="更改密码" :visible.sync="dialogFormVisible" width="500px">
                    <el-form :model="PWDform" :rules="rules" ref="pwdform">
                        <el-form-item label="原始密码"  prop="pwd">
                            <el-input v-model="PWDform.pwd" style="width:50%" type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="新的密码"  prop="password">
                            <el-input v-model="PWDform.password" style="width:50%" type="password"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码"  prop="password2">
                            <el-input v-model="PWDform.password2" style="width:50%" type="password"></el-input>
                        </el-form-item>
                        
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        
                        <el-button @click="closedialog('pwdform')">取 消</el-button>
                        <el-button type="primary" @click="updatePWD('pwdform')">修改</el-button>
                    </div>
                </el-dialog>
        </div>
    </div>
</template>

<script>
export default {
    name: 'baseform',
    inject: ['reload'],
    data() {
        // 员工验证
        var checkTid = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('员工号不能为空'));
            }
            if (!/^(XY)\d{9}$/.test(value)) {
                callback(new Error('员工号格式错误'));
            } else {
                callback();
            }
        };
        //密码比对
        var comparePWD = async (rule, value, callback) => {
            if (!value) {
                return callback(new Error('原始密码不能为空'));
            }
            var d = await this.$http.post('/checkPWD',this.PWDform)

            if(d.code!=200){
                 callback(new Error(d.message));
            }else{
                callback();
            }
        };
        // 密码验证
        var checkPWD = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('密码不能为空'));
            }
            if (!/^[0-9a-zA-Z_]{1,}$/.test(value)) {
                callback(new Error('密码只能由大小写英文字母和数字及下划线组成'));
            } else {
                callback();
            }
        };
        //密码再次校验
        var checkPWD2 = (rule, value, callback) => {
            
            if (!value) {
                return callback(new Error('请再次输入密码'));
            }
            if(value!=this.PWDform.password){
                callback(new Error('密码不匹配!请重新输入'));
              
            }else{
                  callback();
            }
        };
        return {
            dialogFormVisible:false,
            roles: [],
            
            form: {
                id:'',
                nickName:'',
                iconUrl:'',
                status: '01',
                roles: [],
            },
            user:{},
            PWDform:{
                id:'',
                userName:'',
                pwd:'',
                password:'',
                password2:'',
            },
            condition: {
                status: '01'
            },
            dateformat:"yyyy-MM-dd HH:mm:ss",
            rules: {
                tid: [
                    { validator: checkTid,required: true, trigger: 'blur' },
                ],
                pwd:[
                    {validator: comparePWD,required: true,trigger:'blur'},
                ],
                password: [
                    {validator: checkPWD,required: true,trigger:'blur'},
                    {min:6, max:15,message: "密码长度在6-15",trigger:'blur'},
                ],
                password2:[
                    {validator: checkPWD2, required: true,trigger:'blur'}
                ]
            }
        };
    },
    created: function () {
        this.getRoles();
        this.init();
    },
    methods: {

        //图片上传成功后
        handleAvatarSuccess(res, file) {
            this.form.iconUrl=res.message;
        },

        //图片上传前
         beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        //用户信息初始化
        async init(){
          this.user = JSON.parse(window.sessionStorage.getItem("user"));
            this.initform();
        },
        //初始化表单
        initform(){
            this.form.id=this.user.id
            this.form.tid=this.user.tid
            this.form.userName=this.user.userName
            this.form.nickName=this.user.nickName
            this.form.iconUrl=this.user.iconUrl
            this.form.status=this.user.status
            this.PWDform.id=this.user.id
            this.PWDform.userName=this.user.userName
            this.initCheckRole(this.user.roles)
        },
        //初始化选中的角色
        initCheckRole(roles){
            for(var i=0;i<roles.length;i++){
                this.form.roles.push(roles[i].id)
            }
        },
        //获取角色
        async getRoles(){
            var d = await this.$http.post('/roleMap',this.condition)
            if(d.code==200){
                this.roles=d.data
            }else{
                this.$message.error(d.message)
            }
        },
        //添加
        onSubmit(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    var d = await this.$http.put('/user', this.form);
                    if (d.code == 200) {
                        this.$message.success(d.message);
                        this.getUset();
                    } else {
                        this.$message.error(d.message);
                    }
                } else {
                    this.$message.warning('请把内容填写完整!');
                }
            });
        },

        async getUset(){
            var d = this.$http.get("/user/"+this.user.id)
            if (d.code==200) {
                window.sessionStorage.setItem("user",d.data);
            }
        },


        //重置
        reset(formName) {
            this.$confirm('此操作将重置所有信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                   this.initform();
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置'
                    });
            });  
        },
        //关闭密码弹出框
        closedialog(name){
            this.dialogFormVisible = false
            this.$refs[name].resetFields();
        },
        //更改密码
        async updatePWD(name){
           this.$refs[name].validate(async (valid) => {
                if (valid) {
                    var d = await this.$http.put("/user",this.PWDform)
                        if(d.code==200){
                            this.$message.success("修改密码成功!")
                            this.dialogFormVisible = false
                        }else{
                            this.$message.error("修改密码失败!")
                        }
                } else {
                    this.$message.warning('请把内容填写完整!');
                }
            })
           
        },
        goback(){
            this.$router.go(-1);
        },
    }
};
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
     width: 178px;
    height: 178px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>